#include "AppManager.h"

AppManager::AppManager(QObject* parent):QObject{parent},m_controller(nullptr) {
    m_login = new Login();
    connect(m_login,&Login::loginSucceed,this,&AppManager::onLoginSucceed);

    // 初始时，先打开登录页面
    m_login->show();
}

AppManager::~AppManager()
{
    if(m_login){
        m_login->deleteLater();
    }
    if(m_controller){
        m_controller->deleteLater();
    }
}

void AppManager::resetInformation()
{
    QSettings settings("myData.ini",QSettings::IniFormat);
    settings.remove("last_id");
    settings.remove("last_pwd");
    settings.remove("auto_login");
    settings.remove("remember_pwd");

    // 将本地目录下的头像文件删掉
    QString dirPath = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
    QDir dir(dirPath);
    if(dir.exists()){
        QString filePath = dirPath + QDir::separator() + "lastLoginAvatar.png";
        if(QFile::exists(filePath)){
            if (!dir.remove("lastLoginAvatar.png")) {
                qDebug() << "重置登录窗口时，尝试删除文件失败：" << filePath;
            }
        }
    }
}

void AppManager::onLoginSucceed(QString id)
{
    QWebSocket* socket = m_login->getSocket();
    if(!socket->isValid()){
        qDebug()<<"切换主窗口时传递的套接字无效";
        return;
    }

    m_controller = new Controller(id,socket);// 实例化主窗口
    connect(m_controller,&Controller::goBackToLogin,this,&AppManager::onGoBackToLogin);
    // 延迟1秒，让其有时间进行复杂的初始化
    QTimer::singleShot(1000,[=](){
        m_controller->show();
    });

    disconnect(m_login,&Login::loginSucceed,this,&AppManager::onLoginSucceed);
    m_login->hide();
    m_login->deleteLater();
    m_login = nullptr;
}

void AppManager::onGoBackToLogin()
{


    // 重置登录窗口的所有信息（包括配置文件的）
    resetInformation();

    m_login = new Login();
    connect(m_login,&Login::loginSucceed,this,&AppManager::onLoginSucceed);
    m_login->show();

    m_controller->hide();
    disconnect(m_controller,&Controller::goBackToLogin,this,&AppManager::onGoBackToLogin);
    m_controller->deleteLater();
    m_controller = nullptr;
}
